package com.sdp.irrigation.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class HttpClientUtil {

	private HttpClient httpClient;
	
	private MultiThreadedHttpConnectionManager connectionManager;
	
	@Autowired
    private Environment environment;
	
	@PostConstruct
    public void init() {   	
        // 创建连接管理器
        connectionManager = new MultiThreadedHttpConnectionManager();
        
        // 配置连接池参数
        HttpConnectionManagerParams params = connectionManager.getParams();
        params.setMaxTotalConnections(2000); // 最大连接数
        params.setDefaultMaxConnectionsPerHost(1000); // 每个主机最大连接数
        params.setConnectionTimeout(15000); // 连接超时15秒
        params.setSoTimeout(30000); // 读取超时30秒

        // 初始化HttpClient
        httpClient = new HttpClient(connectionManager);
    }
	
	public JSONObject getUserICInfo(String icNo, String idNo) {
		String url = environment.getProperty("sdp.queryBalance");
		if (!StringUtils.isEmpty(url)) {
			JSONObject params = new JSONObject();
			if (!StringUtils.isEmpty(idNo)) {
				params.put("idCard", idNo);
			}
			if (!StringUtils.isEmpty(icNo)) {
				params.put("initCode", icNo);
			}
			String result = this.sendPost(url, params);
			if (!StringUtils.isEmpty(result)) {
				return JSON.parseObject(result);
			}
		} else {
			throw new RuntimeException("sdp.queryBalance配置为空");
		}
		
        return new JSONObject();
	}
	
	@PreDestroy
    public void destroy() {
        // 关闭连接管理器，释放资源
        if (connectionManager != null) {
            connectionManager.shutdown();
        }
    }
	
	private void printLog(Exception e) {
    	log.error(e.getMessage());
        for (StackTraceElement stack : e.getStackTrace()) {
			log.error(stack.toString());
		}
    }
	
	public String sendPost(String url, JSONObject params) {
		InputStream is = null;
        PostMethod postMethod = null;
        BufferedReader br= null;
        try {
        	postMethod = new PostMethod(url);
    		// 设置post请求超时时间
    		postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    		postMethod.addRequestHeader("Content-Type", "application/json");
    		// json格式的参数解析
			if(params != null) {
				RequestEntity entity = new StringRequestEntity(params.toJSONString(), "application/json", "UTF-8");
				postMethod.setRequestEntity(entity);
			}
			httpClient.executeMethod(postMethod);
			
			is = postMethod.getResponseBodyAsStream();
			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String result = "";
			StringBuffer sbf = new StringBuffer();
			while((result = br.readLine())!=null){
			     sbf.append(result);
			}
			return sbf.toString();
		} catch (Exception e) {
			printLog(e);
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (Exception ex) {
				printLog(ex);
			}

            if (postMethod != null) {
            	postMethod.releaseConnection();
			}
		}
        return null;
	}
	
	/**
	 * GET请求
	 * @param url
	 * @return
	 */
	public String sendGet(String url) {
		// 创建GET请求方法实例对象
		GetMethod getMethod = null;
		// 设置post请求超时时间
		BufferedReader br= null;
		InputStream is= null;
		try {
			getMethod = new GetMethod(url);
			getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
			getMethod.addRequestHeader("Content-Type", "application/json");
			httpClient.executeMethod(getMethod);
			is = getMethod.getResponseBodyAsStream();
			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String result = "";
			StringBuffer sbf = new StringBuffer();
			while((result = br.readLine())!=null){
			     sbf.append(result);
			}
			return sbf.toString();
		} catch (Exception e) {
			printLog(e);
		}finally {
			try {
				if (br != null) {
					br.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (Exception ex) {
				printLog(ex);
			}

            if (getMethod != null) {
            	getMethod.releaseConnection();
			}
            
		}
		return null;
	}
	
	public static void main(String[] args) {
		String result = new HttpClientUtil().sendGet("http://127.0.0.1:9292/commserver/CommandDownlinkController/getChannelIdMap");
		System.out.println(result);
//		sendGet("http://111.11.15.235:65000/LAPI/V1.0/System/Security/RSA");
//		sendPost("http://111.11.15.235:65000/LAPI/V1.0/System/Org/QueryByCondition", null);
//		String realm = "c479059a2958";
//		String nonce = "66a2fe49cb441766343b";
//		String ha1 = encryptMD5("admin:"+realm+":Admin@123");
//		System.out.println(ha1);
//		String ha2 = encryptMD5("post:/LAPI/V1.0/System/Org/QueryByCondition");
//		System.out.println(ha2);
//		String response = encryptMD5(ha1+":"+nonce+":"+ha2);
//		System.out.println(response);
		
	}
	
	public static String encryptMD5(String input) {
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(input.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
